package sdk.webview.fmc.com.fmcsdk.check.activity;

import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.EVENT_BUS_NOTIFY_H5_BACK;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.bean.DDTypeBean;
import sdk.webview.fmc.com.fmcsdk.bean.StaffBean;
import sdk.webview.fmc.com.fmcsdk.camera.SystemUtils;
import sdk.webview.fmc.com.fmcsdk.check.adapter.SelectPeopleAdapter;
import sdk.webview.fmc.com.fmcsdk.check.adapter.WorkGroupAdapter;
import sdk.webview.fmc.com.fmcsdk.check.bean.PopupBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.StaffteamBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.WorkStatusBean;
import sdk.webview.fmc.com.fmcsdk.check.dialog.BottomPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.PeopleSelectView;
import sdk.webview.fmc.com.fmcsdk.check.persenter.PeopleSelectPersenter;
import sdk.webview.fmc.com.fmcsdk.util.FastClickHelperClick;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;

public class PeopleSelectActivity extends BaseActivity<PeopleSelectView, PeopleSelectPersenter> implements PeopleSelectView {

    private RecyclerView mRvPeo;
    private SelectPeopleAdapter selectPeopleAdapter;

    private String newStaffStructureId, orgType, projid, baseBizTypeId, id;
    private TextView gong, tvStaffName, tvGroupName, tvSubmit;
    private ImageView ivSel;
    private LinearLayout llRefuse;

    private BottomPopupWindow bottomPopupWindow;
    private BottomPopupWindow submitPopupWindow;
    private BottomPopupWindow redeployReasonPopupWindow;
    private List<StaffteamBean.RecordsDTO> workGroupList = new ArrayList<>();
    private List<DDTypeBean.RecordsBean> reasonList = new ArrayList();
    private List<PopupBean> workGroupNameList = new ArrayList<>();
    private List<PopupBean> redeployReasonList = new ArrayList<>();
    private int mSelectPosition = -1;
    private String staffName = "";
    private String staffId = "";

    private String userName = "";

    private boolean isSelRefuse;

    TextView tvPopupStaffName;
    LinearLayout llNotifyAdmin;
    TextView tvNotifyAdmin;
    EditText etSearch;

    TextView tv_cancel;

    private ImageView iv_clear;

    private String code = "", remake = "", sendStaffId = "", principalId = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_people_select;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        // 在 Activity 的 onCreate() 方法中设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.color_DC3C26)); // 设置状态栏颜色
        }

        newStaffStructureId = getIntent().getStringExtra("staffStructureId");
        orgType = getIntent().getStringExtra("orgType");
        baseBizTypeId = getIntent().getStringExtra("baseBizTypeId");
        projid = getIntent().getStringExtra("projid");
        id = getIntent().getStringExtra("id");
        staffId = getIntent().getStringExtra("planTimeStaffId");
        initView();
        initListener();
        requestApi();
    }

    private void requestApi() {
        //presenter.getWorkStatus(staffStructureId, orgType);
        presenter.getStaffTeamList(projid, baseBizTypeId);
        presenter.getStaff(projid, id);
        presenter.getRedeployReason();
    }


    private void initView() {
        tv_cancel=findViewById(R.id.tv_cancel);
        mRvPeo = findViewById(R.id.rv_peo);
        gong = findViewById(R.id.gong);
        tvStaffName = findViewById(R.id.tv_staff_name);
        tvGroupName = findViewById(R.id.tv_group_name);
        ivSel = findViewById(R.id.iv_sel);
        llRefuse = findViewById(R.id.ll_refuse);
        tvSubmit = findViewById(R.id.tv_submit);
        etSearch = findViewById(R.id.et_search);

        iv_clear = findViewById(R.id.iv_clear);


        mRvPeo.setLayoutManager(new LinearLayoutManager(context));
        selectPeopleAdapter = new SelectPeopleAdapter(null);
        mRvPeo.setAdapter(selectPeopleAdapter);
        selectPeopleAdapter.setEmptyView(View.inflate(context, R.layout.layout_empty, null));
        selectPeopleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                WorkStatusBean.ContactPersonBean item = selectPeopleAdapter.getItem(position);
                if (null != item) {
                    if (isSelRefuse) {
                        changeSelRefuse();
                    }
                    if (mSelectPosition != -1) {
                        if (mSelectPosition == position) {
                            Objects.requireNonNull(selectPeopleAdapter.getItem(mSelectPosition)).isSelect = !Objects.requireNonNull(selectPeopleAdapter.getItem(mSelectPosition)).isSelect;
                            selectPeopleAdapter.notifyItemChanged(mSelectPosition);
                            if (!Objects.requireNonNull(selectPeopleAdapter.getItem(mSelectPosition)).isSelect) {
                                mSelectPosition = -1;
                            }
                        } else {
                            Objects.requireNonNull(selectPeopleAdapter.getItem(mSelectPosition)).isSelect = false;
                            selectPeopleAdapter.notifyItemChanged(mSelectPosition);
                            mSelectPosition = position;
                            Objects.requireNonNull(selectPeopleAdapter.getItem(mSelectPosition)).isSelect = true;
                            selectPeopleAdapter.notifyItemChanged(mSelectPosition);
                        }

                    } else {
                        mSelectPosition = position;
                        Objects.requireNonNull(selectPeopleAdapter.getItem(mSelectPosition)).isSelect = true;
                        selectPeopleAdapter.notifyItemChanged(mSelectPosition);
                    }


                }

            }
        });
    }

    private void initListener() {

        iv_clear.setOnClickListener(v -> {
            etSearch.setText("");
            presenter.getWorkStatus(newStaffStructureId, orgType, "");
            SystemUtils.hideInputmethod(etSearch);
        });

        tv_cancel.setOnClickListener(v -> {
            etSearch.setText("");
            presenter.getWorkStatus(newStaffStructureId, orgType, "");
            SystemUtils.hideInputmethod(etSearch);
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(TextUtils.isEmpty(s.toString())){
                    iv_clear.setVisibility(View.GONE);
                    tv_cancel.setVisibility(View.GONE);
                }else{
                    iv_clear.setVisibility(View.VISIBLE);
                    tv_cancel.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        findViewById(R.id.iv_back).setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.putExtra("isFinish", false);
            setResult(RESULT_OK, intent);
            finish();
            EventBus.getDefault().post(new HandleJsEvent(EVENT_BUS_NOTIFY_H5_BACK, ""));
        });

        findViewById(R.id.tv_peo).setOnClickListener(v -> {
            finish();
        });

        gong.setOnClickListener(this::showBottomPopupWindow);

        llRefuse.setOnClickListener(v -> {
            changeSelRefuse();
        });

        tvSubmit.setOnClickListener(v -> {
            if(!FastClickHelperClick.isFastClick())return;
            if (mSelectPosition != -1 || isSelRefuse) {
                showSubmitPopupWindow(v);
            } else {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_select_personnel));
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // 判断按下的键是否为 "Enter" 键
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 执行回车时的操作，比如提交表单或跳转到下一个输入框
                    String inputText = etSearch.getText().toString();
                    if (TextUtils.isEmpty(inputText)) {
                        inputText = "";
                    }
                    userName = inputText;
                    presenter.getWorkStatus(newStaffStructureId, orgType, userName);

                    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
                    etSearch.clearFocus();

                    SystemUtils.hideInputmethod(etSearch);

                    return true; // 表示事件已经处理
                }
                return false; // 事件未处理，交给系统处理
            }
        });
    }

    private void changeSelRefuse() {
        isSelRefuse = !isSelRefuse;
        if (isSelRefuse) {
            ivSel.setImageResource(R.mipmap.icon_check_red);
            if (mSelectPosition != -1) {
                Objects.requireNonNull(selectPeopleAdapter.getItem(mSelectPosition)).isSelect = false;
                selectPeopleAdapter.notifyItemChanged(mSelectPosition);
                mSelectPosition = -1;
            }

        } else {
            ivSel.setImageResource(R.mipmap.icon_select_no);
        }
    }

    @Override
    protected PeopleSelectPersenter createPresenter() {
        return new PeopleSelectPersenter();
    }

    @Override
    public void getStaffTeamList(StaffteamBean baseData) {
        if (!baseData.getRecords().isEmpty()) {
            workGroupList.clear();
            workGroupList.addAll(baseData.getRecords());
            for (int i = 0; i < workGroupList.size(); i++) {
                if (workGroupList.get(i).getId().equals(newStaffStructureId)) {
                    StaffteamBean.RecordsDTO item = workGroupList.get(i);
                    if (null != item) {
                        mSelectPosition = -1;
                        tvGroupName.setText(item.getDescription());
                        gong.setText(item.getDescription());
                        presenter.getWorkStatus(newStaffStructureId, orgType, userName);

                        //sendStaffId = item.getManagerId();
                        principalId = item.getManagerId();
                    }
                    break;
                }
            }

        }


    }

    @Override
    public void getWoStatusContactPersonList(List<WorkStatusBean.ContactPersonBean> contactPersonList) {
        selectPeopleAdapter.setNewData(contactPersonList);
    }

    @Override
    public void getWorkStaff(StaffBean.StaffData staffData) {
        if (null != staffData) {
            staffName = staffData.getName();
            sendStaffId = staffData.getId();
            tvStaffName.setText(staffName);

            if (StringUtils.isEmpty(sendStaffId) || UserHelper.getUserId().equals(sendStaffId)) {
                llRefuse.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void getRedeployReason(List<DDTypeBean.RecordsBean> records) {
        if (null != records) {
            reasonList.clear();
            reasonList.addAll(records);
        }
    }

    @Override
    public void getQuestRedeploy() {
        ToastUtils.showShort(context, "转派成功");
        Intent intent = new Intent();
        intent.putExtra("isFinish", true);
        setResult(RESULT_OK, intent);
        finish();
    }


    @SuppressLint("SetTextI18n")
    private void showSubmitPopupWindow(View view) {

        if (submitPopupWindow == null) {
            submitPopupWindow = new BottomPopupWindow(context, R.layout.dialog_redeploy);
            View contentView = submitPopupWindow.getContentView();
            tvPopupStaffName = contentView.findViewById(R.id.tv_staff_name);
            llNotifyAdmin = contentView.findViewById(R.id.ll_notify_admin);
            tvNotifyAdmin = contentView.findViewById(R.id.tv_notify_admin);
            CheckBox cbView = contentView.findViewById(R.id.cb_view);
            LinearLayout llResult = contentView.findViewById(R.id.ll_result);
            TextView tvResult = contentView.findViewById(R.id.tv_result);
            cbView.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (!isChecked) {
                    sendStaffId = "";
                }
            });

            llResult.setOnClickListener(v -> {
                showRedeployReasonPopupWindow(view, new OnSelectReasonListener() {
                    @Override
                    public void onClickReason(String reason, int position) {
                        tvResult.setText(reason);
                        remake = reason;
                        code = reasonList.get(position).getCode();
                    }
                });
            });
            contentView.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
                if (submitPopupWindow != null) {
                    // removeDimBackground();
                    submitPopupWindow.dismiss();
                }
            });
            contentView.findViewById(R.id.tv_sure).setOnClickListener(v -> {
                if (!tvResult.getText().toString().isEmpty()) {
                    requestParams();
                } else {
                    ToastUtils.showShort(context, getString(R.string.qiangxuanzezhuan));
                }
            });
        }

        if (llRefuse.getVisibility() == View.VISIBLE) {  //显示了拒单 并且有 负责人（拒单回退给）
            if (isSelRefuse) {
                llNotifyAdmin.setVisibility(View.GONE);
                tvPopupStaffName.setText(staffName);
            } else if (mSelectPosition != -1) {
                WorkStatusBean.ContactPersonBean item = selectPeopleAdapter.getItem(mSelectPosition);
                if (null != item) {
                    tvPopupStaffName.setText(item.getUserName());
                    if(TextUtils.equals(sendStaffId,item.getId()) ){
                        llNotifyAdmin.setVisibility(View.GONE);
                    }else {
                        llNotifyAdmin.setVisibility(View.VISIBLE);
                    }
                }

            }
            tvNotifyAdmin.setText(staffName);
        } else {
            llNotifyAdmin.setVisibility(View.GONE);
            WorkStatusBean.ContactPersonBean item = selectPeopleAdapter.getItem(mSelectPosition);
            if (null != item) {
                tvPopupStaffName.setText(item.getUserName());
            }
        }
        submitPopupWindow.show(view);
    }

    private void requestParams() {

        if (isSelRefuse) {
            principalId = sendStaffId;
        } else {
            if (mSelectPosition != -1) {
                principalId = selectPeopleAdapter.getItem(mSelectPosition).getId();
            }
        }
        String taskId = presenter.getSharedPrefs().getString("taskId", "");
        presenter.getQuestRedeploy(projid, id, taskId, staffId, principalId, remake, sendStaffId, newStaffStructureId, code);
        submitPopupWindow.dismiss();
    }


    private void showRedeployReasonPopupWindow(View view, OnSelectReasonListener listener) {
        if (redeployReasonPopupWindow == null) {
            redeployReasonPopupWindow = new BottomPopupWindow(context, R.layout.dialog_redeploy_reson);
            View contentView = redeployReasonPopupWindow.getContentView();
            TextView tvCancel = contentView.findViewById(R.id.tv_cancel);
            TextView tvTitle = contentView.findViewById(R.id.tv_title);
            tvTitle.setText(getResources().getString(R.string.Reasons_for_transfer));
            RecyclerView rvWorkGroup = contentView.findViewById(R.id.rv_work_group);
            rvWorkGroup.setLayoutManager(new LinearLayoutManager(context));
            redeployReasonList.clear();
            for (DDTypeBean.RecordsBean recordsBean : reasonList) {
                redeployReasonList.add(new PopupBean(recordsBean.getDescription(), false));
            }

            WorkGroupAdapter workGroupAdapter = new WorkGroupAdapter(R.layout.item_work_group, redeployReasonList);
            rvWorkGroup.setAdapter(workGroupAdapter);
            workGroupAdapter.setOnItemClickListener((adapter, view1, position) -> {
                if (null != listener) {
                    workGroupAdapter.setSelect(position);
                    redeployReasonList.get(position).setSelect(true);
                    listener.onClickReason(redeployReasonList.get(position).getName(), position);
                    redeployReasonPopupWindow.dismiss();
                }
            });

            tvCancel.setOnClickListener(v -> {
                redeployReasonPopupWindow.dismiss();
            });
        }


        redeployReasonPopupWindow.show(view);
    }

    private void showBottomPopupWindow(View view) {
        if (bottomPopupWindow == null) {
            bottomPopupWindow = new BottomPopupWindow(context, R.layout.dialog_work_group);
            View contentView = bottomPopupWindow.getContentView();
            TextView tvCancel = contentView.findViewById(R.id.tv_cancel);
            RecyclerView rvWorkGroup = contentView.findViewById(R.id.rv_work_group);
            rvWorkGroup.setLayoutManager(new LinearLayoutManager(context));
            workGroupNameList.clear();
            for (StaffteamBean.RecordsDTO recordsDTO : workGroupList) {
                if (gong.getText().toString().equals(recordsDTO.getDescription())) {
                    workGroupNameList.add(new PopupBean(recordsDTO.getDescription(), true));
                } else {
                    workGroupNameList.add(new PopupBean(recordsDTO.getDescription(), false));
                }

            }
            WorkGroupAdapter workGroupAdapter = new WorkGroupAdapter(R.layout.item_work_group, workGroupNameList);
            rvWorkGroup.setAdapter(workGroupAdapter);

            workGroupAdapter.setOnItemClickListener((adapter, view1, position) -> {
                StaffteamBean.RecordsDTO item = workGroupList.get(position);
                if (null != item) {
                    mSelectPosition = -1;
                    newStaffStructureId = item.getId();
                    tvGroupName.setText(item.getDescription());
                    gong.setText(item.getDescription());
                    presenter.getWorkStatus(newStaffStructureId, orgType, userName);
                    bottomPopupWindow.dismiss();

                    sendStaffId = item.getManagerId();

                    int index = -1;
                    for (int i = 0; i < workGroupNameList.size(); i++) {
                        if (workGroupNameList.get(i).isSelect()) {
                            index = i;
                            break;
                        }
                    }
                    if (index != -1) {
                        workGroupNameList.get(index).setSelect(false);
                        workGroupAdapter.notifyItemChanged(index);
                    }


                    workGroupNameList.get(position).setSelect(true);
                    workGroupAdapter.notifyItemChanged(position);

                }


            });
            tvCancel.setOnClickListener(v -> {
                bottomPopupWindow.dismiss();
            });

        }
//        assert workGroupAdapter != null;
//        workGroupAdapter.setSelectPosition(selectPostion);
//        workGroupAdapter.notifyItemChanged(selectPostion);
        bottomPopupWindow.show(view);
    }


    public interface OnSelectReasonListener {
        void onClickReason(String reason, int position);
    }

}
